package cn.datawin.routeserver.input.action;

import cn.datawin.bms.customer.redis.CstmCustomerCmppRedisDto;
import cn.datawin.bms.provider.redis.ProvProviderChannelRedisDto;
import cn.datawin.constant.RocketMqConstant;
import cn.datawin.routeserver.input.machine.Basket;
import cn.datawin.routeserver.input.service.ProduceService;
import cn.datawin.sms.cmpp2.SmsDetailLog;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.squirrelframework.foundation.fsm.UntypedAnonymousAction;
import org.squirrelframework.foundation.fsm.UntypedStateMachine;

import java.util.Map;

@Slf4j
public class SubmitAction extends UntypedAnonymousAction {
	@Override
	public void execute(Object ruleFrom, Object ruleTo, Object event, Object context, UntypedStateMachine stateMachine) {

		Basket basket = (Basket) context;
		SmsDetailLog smsDetailLog = basket.getSmsDetailLog();


		//1、设置供应商通道id、供应商id、供应商code、供应商spCode
		ProvProviderChannelRedisDto selectChannel = basket.getSelectChannel();
		smsDetailLog.setProvProviderChannelId(selectChannel.getId()+"");
		smsDetailLog.setProvProviderId(selectChannel.getProviderId()+"");
		smsDetailLog.setProvProviderCode(selectChannel.getProvinceCode());
		Map<String, String> providerParams = selectChannel.getProviderParams();
		String providerSpCode = providerParams.get("spCode");
		if (StrUtil.isNotBlank(providerSpCode)) {
			smsDetailLog.setProvProviderSpCode(providerSpCode);
		}

		//2、剥离inputLog中的subCode,原始结构为用户的spCode+客户补充码
		CstmCustomerCmppRedisDto cstmCustomerCmppRedisDto = basket.getCstmCustomerCmppRedisDto();
		String subCode = smsDetailLog.getSubCode();
		String spCode = cstmCustomerCmppRedisDto.getSpCode();
		if (StrUtil.isNotBlank(spCode) && StrUtil.isNotBlank(subCode)) {
			if (subCode.startsWith(spCode)) {
				String newSubCode = subCode.substring(spCode.length());
				smsDetailLog.setSubCode(newSubCode);
			}
		}

		//3、单号码计费条数 deductions
		int sc = smsDetailLog.getContent().length();
		int wul = 67;
		int deductions = 1;
		if (sc > 70) {
			deductions = sc % wul == 0 ? (sc / wul) : (sc / wul) + 1;
		}
		smsDetailLog.setDeductions(deductions);

		//4、根据providerApiProgramId（通道的接入方式，cmpp、sgip）将输入的短信内容投送到对应的服务器
		Long providerApiProgramId = selectChannel.getProviderApiProgramId();
		if (providerApiProgramId==1){
			//获取outputServerTag
			String pkey = providerParams.get("pkey");
			smsDetailLog.setOutputServerTag(pkey);
			//将短信内容投送到对应的服务器
			//根据pkey获取cmpp-client服务器信息
			SpringUtil.getBean(ProduceService.class).sendSubmitMessage(RocketMqConstant.SMS_CMPP_SUBMIT_TOPIC,smsDetailLog, pkey);
		}




	}
}
